package com.yksj.healthtalk.ui.salon;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshScrollView;
import org.json.JSONException;
import org.json.JSONObject;
import org.universalimageloader.core.ImageLoader;
import org.universalimageloader.utils.StorageUtils;

import sfs2x.client.core.SFSEvent;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.yksj.healthtalk.adapter.salonInfoTypeAdapter;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.comm.SearchByTagActivity;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.db.ChatUserHelper;
import com.yksj.healthtalk.entity.GroupInfoEntity;
import com.yksj.healthtalk.entity.TagEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.chatting.ChatActivity;
import com.yksj.healthtalk.ui.interestwall.TagChooseActivity;
import com.yksj.healthtalk.ui.salon.SalonSelectPaymentOptionActivity.OnBuyTicketHandlerListener;
import com.yksj.healthtalk.utils.BitmapUtils;
import com.yksj.healthtalk.utils.CollectUtils;
import com.yksj.healthtalk.utils.SalonHttpUtil;
import com.yksj.healthtalk.utils.ToastUtil;
import com.yksj.healthtalk.utils.WheelUtils;
import com.yksj.healthtalk.utils.XmlCategoryParserUtils;

/**
 * 话题查看自己的
 * 
 * @author Administrator
 * 
 */
public class SalonReadSelf extends BaseFragmentActivity implements OnClickListener,
		OnCheckedChangeListener, OnItemClickListener,
		OnBuyTicketHandlerListener, OnRefreshListener<ScrollView> {

	private GroupInfoEntity entity;
	private ImageView mSalonLevels;// 话题的等级
	private ImageView mSalonCharge;
	private ImageView mSalonDoctor;
	private EditText mSalonNote;
	private EditText mSalonName;
	private ToggleButton pushNotificationToggleButton;// 是否推送消息
	private ToggleButton isPublicCustInfoToggleButton;// 接受消息厅开放
	private TextView mTitleName;
	private List<String> strs;// 标签数据
	private StringBuilder tagId;
	private StringBuilder upperId;
	private StringBuilder tagName;
	private ArrayList<TagEntity> tags;// 标签返回类型
	private ArrayList<TagEntity> bufferTags;
	private GridView mGridView;
	private String[] subclassNames;
	private String[] subclassIds;
	private salonInfoTypeAdapter adapter;
	private Button titleRightBtn;
	private String path = "";
	private File storageFile;
	private ImageLoader mImageLoader;
	private Button titleBackBtn;
	private ImageView mSalonIcon;// 用户头像
	private Set<String> deleteRepeatSet;// 大类去重
	private String updateInfoJsonToStr;// 修改话题的字符串数据
	private boolean infoChange = false;// 资料是否修改
	private String cachePath = "";
	private LinearLayout salonManagementLin;
	protected ImageView att_iv;
	private TextView att_tv;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case WHAT_FAILE:
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				ToastUtil.showShort(SalonReadSelf.this, (String) msg.obj);
				finish();
				break;
			case WHAT_SUCC:
				// 保存成功
				salonManagementLin.setVisibility(View.VISIBLE);
				downLin.setVisibility(View.VISIBLE);
				titleRightBtn.getBackground().setLevel(0);// 显示编辑按钮
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				if (SmartFoxClient.getLoginUserId() != null) {
					GroupInfoEntity entity = SalonHttpUtil
							.jsonAnalysisSalonEntity(SalonReadSelf.this,
									(String) msg.obj).get(0);
					HTalkApplication.getAppData().updateCacheInfomation(entity);
					ChatUserHelper.getInstance().saveGroupInfo(
							SalonReadSelf.this, entity,
							SmartFoxClient.getLoginUserId());
					initInfo(entity);
				} else {
					ToastUtil.showShort(SalonReadSelf.this, "你还没有登录");
				}
				break;
			}
			super.handleMessage(msg);
		}
	};

	public static final int CAMERA_REQUESTCODE = 0;
	private static final int PHOTO_PICKED_WITH_DATA = 1;
	private static final int TAG_CHOOSE_REQUESTCODE = 2;
	private final int WHAT_FAILE = -1;
	private final int WHAT_SUCC = 1;
	private PopupWindow mPopupWindow;
	private TextView ticketTextView;
	private TextView fileTextView;
	private TextView incomeTextView;
	private TextView salonTextView;
	private LinearLayout downLin;
	private LinearLayout talkLin;
	private LinearLayout unfollowLin;
	private BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_COLLECT_GROUP_NOT)) {
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(SalonReadSelf.this,
							R.string.groupNewFail);
				} else {
					entity.setSalonAttention(false);
					ToastUtil.showShort(SalonReadSelf.this, "取消关注成功");
					// 联系人不存在该联系人 则从数据库中删除该群
					HTalkApplication.getAppData().removeCacheInfomation(entity);
					CollectUtils.deleteSalon(chatUserHelper,
							entity.getId());
					mAppData.getCreatedGroupIdList().remove(entity.getId());
				}
			} else if (action.equals(MessagePushService.ACTION_COLLECT_GROUP)) {
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(SalonReadSelf.this,
							R.string.groupNewFail);
				} else {
					entity.setSalonAttention(true);
					ToastUtil.showShort(SalonReadSelf.this, "关注成功");
					chatUserHelper.saveGroupInfo(context, entity,
							entity.getId());
					mAppData.getCreatedGroupIdList().add(0, entity.getId());
					HTalkApplication.getAppData().updateCacheInfomation(entity);
				}
			} else if (action.equals(SFSEvent.CONNECTION_LOST)) {
				SmartFoxClient.getSmartFoxClient().doConnecion();
			}
			// 是取消关注还是关注
			if (entity.isSalonAttention() == true) {
				att_iv.setImageResource(R.drawable.person_quxiao_guanzhu);
				att_tv.setText(R.string.cancelCollect);
			} else {
				att_iv.setImageResource(R.drawable.person_guanzhu);
				att_tv.setText(R.string.atention);
			}
		}
	};
	private AppData mAppData;
	private ChatUserHelper chatUserHelper;
	private PullToRefreshScrollView mPullRefreshScrollView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN
						| WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		setContentView(R.layout.salon_read_self);
		mAppData = HTalkApplication.getAppData();
		chatUserHelper = ChatUserHelper.getInstance();
		init();
		queryData();
	}

	@Override
	protected void onStart() {
		IntentFilter filter = new IntentFilter(
				MessagePushService.ACTION_GROUPLIST);
		// 取消关注的过滤器
		filter.addAction(MessagePushService.ACTION_COLLECT_GROUP_NOT);
		filter.addAction(MessagePushService.ACTION_COLLECT_GROUP);
		registerReceiver(receiver, filter);
		super.onStart();
	}

	@Override
	protected void onStop() {
		unregisterReceiver(receiver);
		super.onStop();
	}

	/**
	 * 请求的数据
	 */
	private void queryData() {
		deleteRepeatSet = new HashSet<String>();
		if (getIntent().hasExtra("PersonInfo")) {
			entity = getIntent().getExtras().getParcelable("PersonInfo");
			initInfo(entity);
		} else if (getIntent().hasExtra("id")) {
			HttpRestClient.doHttpSalonToId(SmartFoxClient.getLoginUserId(),
					getIntent().getExtras().getString("id"),
					new ObjectHttpResponseHandler() {
						@Override
						public Object onParseResponse(String content) {
							GroupInfoEntity entity = null;
							if ("N".equals(content)) {
								ToastUtil.showShort(SalonReadSelf.this, content);
							} else {
								entity = SalonHttpUtil.jsonAnalysisSalonEntity(
										content).get(0);
							}
							return entity;
						}
						@Override
						public void onSuccess(int statusCode, Object response) {
							super.onSuccess(statusCode, response);
							if (response != null
									&& response instanceof GroupInfoEntity) {
								entity = (GroupInfoEntity) response;
							}
							initInfo(entity);
						}
						@Override
						public void onStart() {
							if (mPullRefreshScrollView != null && !mPullRefreshScrollView.isRefreshing()) {
								mPullRefreshScrollView.setRefreshing();
							}
							super.onStart();
						}
						@Override
						public void onFinish() {
							mPullRefreshScrollView.onRefreshComplete();
							super.onFinish();
						}
					});
		}
	}

	private void initInfo(GroupInfoEntity entity) {
		if (entity == null) {
			ToastUtil.showShort(SalonReadSelf.this, R.string.value_error);
			return;
		}
		// 控件数据
		mImageLoader = ImageLoader.getInstance();
		// 话题等级
		int level;
		if ((level = Integer.valueOf(entity.getGroupLevel())) > 0) {
			mSalonLevels.getDrawable().setLevel(level);
		} else {
			mSalonLevels.setVisibility(View.GONE);
		}

		widgetEnabled(Integer.valueOf(entity.getGroupLevel()));

		// 是否收费
		if (!entity.isCharge()) {
			mSalonCharge.setVisibility(View.GONE);
		}

		// 判断是否是医师话题
		if (!entity.isSalon()) {
			mSalonDoctor.setVisibility(View.GONE);
		}

		// 签名
		mSalonNote.setText(entity.getRecordDesc());
		mSalonNote.setEnabled(false);
		// 话题名称
		mSalonName.setText(entity.getName());
		mSalonName.setBackgroundColor(Color.WHITE);
		mSalonName.setEnabled(false);
		// 话题标题
		mTitleName.setText(entity.getName());

		// 用户头像
		mImageLoader.displayImage("4",entity.getNormalHeadIcon(),mSalonIcon);
		mSalonIcon.setClickable(false);

		// 标签处理
		tagId = new StringBuilder();
		upperId = new StringBuilder();
		tagName = new StringBuilder();
		bufferTags = new ArrayList<TagEntity>();
		strs = new ArrayList<String>();
		// 遍历标签数据
		String InfoLayName = entity.getInfoLayName();
		String infoIds = entity.getInfoId();
		subclassNames = InfoLayName.split(",");
		subclassIds = infoIds.split(",");
		for (int i = 0; i < subclassNames.length; i++) {
			if (!subclassIds[i].equals("")) {
				// strs.add(subclassNames[i]);
				TagEntity entity1 = XmlCategoryParserUtils.queryTagEntity(
						getResources(), R.xml.salon_label, subclassIds[i]);
				if (entity1 != null) {
					bufferTags.add(entity1);
				}
			}
		}

		adapter = new salonInfoTypeAdapter(this, strs);
		adapter.setAddBtnVisable(false);
		mGridView.setAdapter(adapter);

		// 标签右边的编辑按钮
		titleRightBtn.setBackgroundResource(R.layout.salon_edit);
		titleRightBtn.getBackground().setLevel(0);
		// 是否接受消息推送
		if (entity.isInceptMessage() == true) {
			pushNotificationToggleButton.setChecked(true);
		} else {
			pushNotificationToggleButton.setChecked(false);
		}

		// 对消息厅开放
		if (entity.getIsReleaseSystemMessage()) {
			isPublicCustInfoToggleButton.setChecked(true);
		} else {
			isPublicCustInfoToggleButton.setChecked(false);
		}
//		pushNotificationToggleButton.setEnabled(false);
//		isPublicCustInfoToggleButton.setEnabled(false);

		// 是取消关注还是关注
		if (entity.isSalonAttention() == true) {
			att_iv.setImageResource(R.drawable.person_quxiao_guanzhu);
			att_tv.setText("取消关注");
		} else {
			att_iv.setImageResource(R.drawable.person_guanzhu);
			att_tv.setText("关注");
		}
		// 初始化json数据 判断资料是否修改
		try {
			getTags(bufferTags);
			JSONObject object = jsonToHttp(mSalonName.getText().toString()
					.trim(), mSalonNote.getText().toString().trim());
			updateInfoJsonToStr = object.toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 初始化UI并赋值
	 */
	private void init() {
		// findViewById(R.id.title_back).setOnClickListener(this);
		titleBackBtn = (Button) findViewById(R.id.title_back);
		mTitleName = (TextView) findViewById(R.id.title_lable);
		titleRightBtn = (Button) findViewById(R.id.title_right2);
		mSalonIcon = (ImageView) findViewById(R.id.salon_icon);
		mSalonName = (EditText) findViewById(R.id.salon_name);
		mSalonLevels = (ImageView) findViewById(R.id.salon_dengji);
		mSalonCharge = (ImageView) findViewById(R.id.money);
		mSalonDoctor = (ImageView) findViewById(R.id.isDoctor_x);
		mSalonNote = (EditText) findViewById(R.id.miaoshu);
		pushNotificationToggleButton = (ToggleButton) findViewById(R.id.info_salon_toggleBtn);
		isPublicCustInfoToggleButton = (ToggleButton) findViewById(R.id.info_toggleBtn);
		mGridView = (GridView) findViewById(R.id.label_gv);
		ticketTextView = (TextView) findViewById(R.id.ticket_tv);
		fileTextView = (TextView) findViewById(R.id.file_tv);
		incomeTextView = (TextView) findViewById(R.id.income_tv);
		salonTextView = (TextView) findViewById(R.id.salon_tv);
		att_iv = (ImageView) findViewById(R.id.att_iv);
		att_tv = (TextView) findViewById(R.id.att_tv);
		downLin = (LinearLayout) findViewById(R.id.downLin);
		talkLin = (LinearLayout) findViewById(R.id.talk_lin);
		unfollowLin = (LinearLayout) findViewById(R.id.unfollow_lin);
		salonManagementLin = (LinearLayout) findViewById(R.id.salon_management);
		mPullRefreshScrollView = (PullToRefreshScrollView) findViewById(R.id.pull_refresh_scrollview);

		mTitleName.setOnClickListener(this);
		findViewById(R.id.salon_member).setOnClickListener(this);
		findViewById(R.id.ticket_set).setOnClickListener(this);
		findViewById(R.id.file_manager).setOnClickListener(this);
		findViewById(R.id.shourutongji).setOnClickListener(this);
		pushNotificationToggleButton.setOnCheckedChangeListener(this);
		isPublicCustInfoToggleButton.setOnCheckedChangeListener(this);
		mSalonIcon.setOnClickListener(this);
		mPullRefreshScrollView.setOnRefreshListener(this);
		mSalonLevels.setOnClickListener(this);
		mGridView.setOnItemClickListener(this);
		titleBackBtn.setOnClickListener(this);
		talkLin.setOnClickListener(this);
		titleRightBtn.setVisibility(View.VISIBLE);
		titleRightBtn.setOnClickListener(this);
		unfollowLin.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		Intent intent = null;
		switch (v.getId()) {
		case R.id.salon_icon:// 修改话题头像
			showuploadPopWindow();
			break;
		case R.id.salon_dengji:// 话题的等级展示

			break;
		case R.id.salon_member:// 话题成员
			intent = new Intent(this, SalonMemberListActivity.class);
			intent.putExtra("groupId", entity.getId());
			startActivity(intent);
			break;
		case R.id.ticket_set:// 门票设置
			intent = new Intent(SalonReadSelf.this,SalonTicketActivity.class);
			intent.putExtra("groupId", entity.getId());// 话题的id
			startActivity(intent);
			break;
		case R.id.file_manager:// 文件管理
			SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(),
					 getString(R.string.stay_tuned)
					);
			break;
		case R.id.shourutongji:// 收入统计
			intent = new Intent(SalonReadSelf.this, SalonInComeActivity.class);
			intent.putExtra("groupId", entity.getId());
			startActivity(intent);
			break;
		case R.id.title_right2:// 话题介绍页
			if (titleRightBtn.getBackground().getLevel() == 0) {
				titleRightBtn.getBackground().setLevel(1);// 显示保存按钮
				salonManagementLin.setVisibility(View.GONE);
				downLin.setVisibility(View.GONE);
				pushNotificationToggleButton.setEnabled(true);
				isPublicCustInfoToggleButton.setEnabled(true);
				mSalonIcon.setClickable(true);// 头像可以点击
				mSalonName.setEnabled(true);
				mSalonName.setBackgroundResource(R.drawable.dise);
				mSalonNote.setEnabled(true);
				adapter.setAddBtnVisable(true);
				adapter.notifyDataSetChanged();
			} else {
				try {
					if (!cachePath.equals(path)
							|| isInfoChanged(jsonToHttp(
									mSalonName.getText().toString().trim(),
									mSalonNote.getText().toString().trim())
									.toString())) {
						infoChange = true;
						createGroup();
					} else {
						titleRightBtn.getBackground().setLevel(0);// 显示编辑按钮
						salonManagementLin.setVisibility(View.VISIBLE);
						downLin.setVisibility(View.VISIBLE);
						mSalonIcon.setClickable(false);// 头像不可以点击
						adapter.setAddBtnVisable(false);
						mSalonName.setBackgroundColor(Color.TRANSPARENT);
						mSalonName.setEnabled(false);
						mSalonNote.setEnabled(false);
						adapter.notifyDataSetChanged();
					}
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
			break;
		case R.id.galleryadd:
			intent = getPhotoPickIntent();
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
			if (mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
			}
			break;
		case R.id.cameraadd:
			Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			storageFile = StorageUtils.createCameraFile();
			if (storageFile == null) {
				ToastUtil.showShort(this, "内存卡不可用");
				return;
			}
			Uri uri = Uri.fromFile(storageFile);
			intent2.putExtra(MediaStore.EXTRA_OUTPUT, uri);
			startActivityForResult(intent2, CAMERA_REQUESTCODE);
			if (mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
			}
			break;
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.cancel:
			if (mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
			}
			break;
		case R.id.talk_lin:
			SalonHttpUtil.onItemClick(this, this, getSupportFragmentManager(),
					entity, true);
			break;
		case R.id.unfollow_lin://关注 取消关注
			if (entity.isSalonAttention()) {
				SmartFoxClient.sendStrRequest(
						SmartFoxClient.RequestCode.COLLECT_GROUP_NOT,
						entity.getId());
			} else {
				SmartFoxClient.sendStrRequest(
						SmartFoxClient.RequestCode.COLLECT_GROUP,
						entity.getId());
			}
			break;
		}

	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	public static Intent getPhotoPickIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 80);
		intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		return intent;
	}

	/**
	 * 选择弹出框
	 */
	public void showuploadPopWindow() {
		LayoutInflater inflater = LayoutInflater.from(this);
		View view = inflater.inflate(R.layout.interest_image_add_action, null);
		View mainView = inflater.inflate(R.layout.interest_content, null);
		if (mPopupWindow == null) {
			mPopupWindow = new PopupWindow(view, LayoutParams.FILL_PARENT,
					LayoutParams.WRAP_CONTENT);
		}
		WheelUtils.setPopeWindow(this, mainView, mPopupWindow);
		Button cameraAdd = (Button) view.findViewById(R.id.cameraadd);
		Button galleryAdd = (Button) view.findViewById(R.id.galleryadd);
		Button cancel = (Button) view.findViewById(R.id.cancel);

		cameraAdd.setOnClickListener(this);
		galleryAdd.setOnClickListener(this);
		cancel.setOnClickListener(this);
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		boolean inceptMessage = pushNotificationToggleButton.isChecked();
		boolean releaseSystemMessage = isPublicCustInfoToggleButton.isChecked();
		switch (buttonView.getId()) {
		case R.id.info_salon_toggleBtn:// 消息推送
		case R.id.info_toggleBtn:// 发言是否对消息厅开放
//			if (titleRightBtn != null
//					&& titleRightBtn.getBackground().getLevel() == 1) {
//				SalonHttpUtil.updateGroupInceptMsg(getSupportFragmentManager(),
//						SalonReadSelf.this, SmartFoxClient.getLoginUserId(),
//						entity.getId(), inceptMessage, releaseSystemMessage);
//			}
			SalonHttpUtil.updateGroupInceptMsg(getSupportFragmentManager(),
					SalonReadSelf.this, SmartFoxClient.getLoginUserId(),
					entity.getId(), inceptMessage, releaseSystemMessage);
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		if (position == strs.size()) {
			Intent intent = new Intent(SalonReadSelf.this,
					TagChooseActivity.class);
			if (bufferTags != null && bufferTags.size() > 0) {
				intent.putParcelableArrayListExtra("tags", bufferTags);
			}
			intent.putExtra("resid", R.xml.salon_label);
			startActivityForResult(intent, TAG_CHOOSE_REQUESTCODE);
		} else {
			GroupInfoEntity mGroupInfoEntity = new GroupInfoEntity();
			mGroupInfoEntity.setInfoId(bufferTags.get(position).getId());
			mGroupInfoEntity.setInfoLayName(bufferTags.get(position).getName());
			mGroupInfoEntity.setCreateCustomerID(SmartFoxClient
					.getSmartFoxClient().getUserId());
			Intent intent = new Intent(SalonReadSelf.this,
					SearchByTagActivity.class);
			intent.putExtra("entity", mGroupInfoEntity);
			startActivity(intent);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case CAMERA_REQUESTCODE:
			if(resultCode == Activity.RESULT_OK){
				try {
					Bitmap bm = BitmapUtils.decodeBitmap(storageFile.getAbsolutePath(),
							900, 900);
					File file = StorageUtils.createHeaderFile();
					StorageUtils.saveImageOnImagsDir(bm, file);
					path = file.getAbsolutePath();
					mSalonIcon.setImageBitmap(bm);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			break;
		case PHOTO_PICKED_WITH_DATA:
		if(resultCode == Activity.RESULT_OK){
			try{
				Bitmap photo = data.getParcelableExtra("data");
				File file = StorageUtils.createHeaderFile();
				StorageUtils.saveImageOnImagsDir(photo, file);
				path = file.getAbsolutePath();
				mSalonIcon.setImageBitmap(photo);
			}catch(Exception e){
				e.printStackTrace();
			}
			}
			break;
		case TAG_CHOOSE_REQUESTCODE:
		if(resultCode == Activity.RESULT_OK){

			tags = data.getParcelableArrayListExtra("tags");
			bufferTags.clear();
			strs.clear();
			bufferTags.addAll(tags);
			initTags();
			getTags(tags);
			adapter.notifyDataSetChanged();
			}
			break;
		
		}
		
	}

	/**
	 * 创建话题
	 */
	public void createGroup() {
		// TODO Auto-generated method stub
		final String name = mSalonName.getText().toString();
		final String describe = mSalonNote.getText().toString();
		if (name.trim().equals("")) {
			Toast.makeText(this, getString(R.string.inputThemeName),
					Toast.LENGTH_SHORT).show();
			return;
		}

		if (name.trim().length() > 40) {
			Toast.makeText(this, getString(R.string.inputThemeLength),
					Toast.LENGTH_SHORT).show();
			return;
		}

		if (describe.trim().length() > 1000) {
			Toast.makeText(this, getString(R.string.inputDescLength),
					Toast.LENGTH_SHORT).show();
			return;
		}

		if (describe.trim().equals("")) {
			Toast.makeText(this, getString(R.string.inputAddDesc),
					Toast.LENGTH_SHORT).show();
			return;
		}

		if (tagId.toString().trim().equals("")) {
			ToastUtil.showShort(SalonReadSelf.this, R.string.choice_tag);
			return;
		}
		// 判断资料是否修改过
		try {
			JSONObject json = jsonToHttp(name, describe);
				HttpRestClient.doHttpNewSalon(SalonReadSelf.this,
						json.toString(), path,	new AsyncHttpResponseHandler(this) {
							public void onSuccess(int statusCode,	String content) {
								isRequestSuccess(content);
							}
					
						});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 创建话题成功
	 * 
	 * @param content
	 */
	private void isRequestSuccess(String content) {
		if (content == null || "".equals(content) || !content.contains("{")) {
			Message message = handler.obtainMessage();
			message.what = WHAT_FAILE;
			handler.sendMessage(message);
			return;
		} else {
			Message message = handler.obtainMessage();
			message.obj = content;
			message.what = WHAT_SUCC;
			handler.sendMessage(message);
		}
	};

	/**
	 * 修改话题的Json数据
	 * 
	 * @param name
	 * @param describe
	 * @return
	 * @throws JSONException
	 */
	private JSONObject jsonToHttp(final String name, final String describe)
			throws Exception {
		String userFileName = "0";
		JSONObject json = new JSONObject();
		json.put("groupId", entity.getId());
		json.put("userFileName", userFileName);
		json.put("recordName", name);
		json.put("record_desc", describe);
		json.put("infoLayid", tagId.toString().trim());
		json.put("limitNumber", "");
		json.put("inceptMessage",
				pushNotificationToggleButton.isChecked() ? "Y" : "N");
		json.put("upperLayid", upperId.toString().trim());
		// 是否将消息发布到消息厅(1-发布，0-不发布)
		json.put("releaseSystemMessage",
				isPublicCustInfoToggleButton.isChecked() ? "1" : "0");
		json.put("custId", SmartFoxClient.getLoginUserId());
		json.put("publicCustInfo", "Y");
		try {
			json.put("infoLayName", tagName.toString().trim());
		} catch (Exception e) {
		}
		json.put("groupClass", entity.isSalon() ? 1 : 2);
		return json;
	}

	/**
	 * 判断资料是都修改
	 * 
	 * @param str
	 * @return
	 */
	private Boolean isInfoChanged(String str) {
		if (updateInfoJsonToStr != null && str != null
				&& updateInfoJsonToStr.equals(str)) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 标签初始化
	 */
	private void getTags(ArrayList<TagEntity> tags) {
		Boolean b;
		for (TagEntity t : tags) {
			b = deleteRepeatSet.add(t.getUpperId());
			strs.add(t.getName());
			if (!t.getId().equals("0") && !t.getId().equals("")) {
				tagId.append(t.getId()).append(",");
			}
			if (b != false) {
				upperId.append(t.getUpperId()).append(",");
			}
			tagName.append(t.getName()).append(",");
		}
		if (tagId.length() != 0) {
			tagId.deleteCharAt(tagId.length() - 1);
		}
		if (upperId.length() >= 1) {
			upperId.deleteCharAt(upperId.length() - 1);
		}
		if (tagName.length() >= 1) {
			tagName.deleteCharAt(tagName.length() - 1);
		}
	}

	/**
	 * 初始化标签
	 */
	private void initTags() {
		// TODO Auto-generated method stub
		deleteRepeatSet.clear();
		strs.clear();
		tagId.delete(0, tagId.length() - 1 <= 0 ? 0 : tagId.length());
		upperId.delete(0, upperId.length() - 1 <= 0 ? 0 : upperId.length());
		tagName.delete(0, tagName.length() - 1 <= 0 ? 0 : tagName.length());
	}

	/**
	 * 
	 * @param salonLevel
	 *            话题等级
	 */
	@SuppressLint("ResourceAsColor")
	public void widgetEnabled(int salonLevels) {
		 if (SmartFoxClient.getLoginUserInfo().isDoctor() && entity.isSalon()) {
			    findViewById(R.id.ticket_set).setEnabled(true);
				findViewById(R.id.file_manager).setEnabled(true);
				findViewById(R.id.shourutongji).setEnabled(true);
				salonTextView.setTextColor(Color.BLACK);
				incomeTextView.setTextColor(Color.BLACK);
				fileTextView.setTextColor(Color.BLACK);
				ticketTextView.setTextColor(Color.BLACK);
				salonTextView.setTextColor(Color.BLACK);
		 } else {
			 findViewById(R.id.ticket_set).setEnabled(false);
			 findViewById(R.id.file_manager).setEnabled(false);
			 findViewById(R.id.shourutongji).setEnabled(false);
			 salonTextView.setTextColor(R.color.tab_txt_gray);
			 incomeTextView.setTextColor(R.color.tab_txt_gray);
			 fileTextView.setTextColor(R.color.tab_txt_gray);
			 ticketTextView.setTextColor(R.color.tab_txt_gray);
			 salonTextView.setTextColor(Color.BLACK);
		 }
	}

	@Override
	public void onTicketHandler(String state, GroupInfoEntity entity) {
		if ("0".equals(state)) {
		} else if ("-1".equals(state)) {
			ToastUtil.showShort(this, "服务器出错");
		} else {
			Intent intent1 = new Intent();
			intent1.putExtra(ChatActivity.KEY_PARAME, entity);
			intent1.setClass(this, ChatActivity.class);
			startActivity(intent1);
		}
	}

	@Override
	public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
		queryData();
	};

}
